/* model */
import Role from "@model/entity/Role/Role";
import { 
  BizRoleSelectOption, 
  ProductLineRoleMap 
} from "@src/component/business/BizRoleSelect/model";
import { 
  isHaveBusinessServiceCloudProductLine, 
  isHaveCustomerServiceCloudProductLine, 
  roleListGroupByProductLineToMap, 
  validateNeedExtraHandleRoleList
} from "@shb-lib/tenant";
/* util */
import { isArray, isFalsy } from "@src/util/type";
/* enum */
import { SHBProductLineEnum } from "@shb-lib/tenant";

type TransformRoleListOptionsType = {
  // 是否只显示 服务云 角色
  isOnlyShowBusinessServiceCloudRole?: boolean;
}

function roleToOption(role: Role): BizRoleSelectOption {
  return {
    ...role,
    label: role?.text || role.name,
    value: role.id,
    children: isArray(role.children) ? rolesToOptions(role!.children as Role[]) : []
  }
}

function rolesToOptions(roles: Role[]): BizRoleSelectOption[] {
  return roles.map(roleToOption)
}

/** 
 * @description 转换角色列表数据，适应不同产品线
*/
function transformRoleList(roleList: Role[], options?: TransformRoleListOptionsType): Role[] {
  
  const { isNotNeedExtraHandleRole, productLineMap, _isHaveBusinessServiceCloudProductLine } = validateNeedExtraHandleRoleList(roleList)
  
  // 如果没有 客服云 或 服务云 产品线，则返回原始数据，不做处理
  if (isNotNeedExtraHandleRole) {
    return roleList;
  }
  
  // 是否配置了只显示 服务云 角色
  const isOnlyShowBusinessServiceCloudRole = Boolean(options?.isOnlyShowBusinessServiceCloudRole);
  
  /** 
   * 如果有服务云版本角色 且 配置了只显示 服务云 角色，
   * 则返回 服务云 角色列表 和 待分配 角色列表
  */
  if (_isHaveBusinessServiceCloudProductLine && isOnlyShowBusinessServiceCloudRole) {
    return productLineMap[SHBProductLineEnum.BusinessServiceCloud];
  }
  
  const productLineRoleKeys = Object.keys(ProductLineRoleMap)
  const newRoleList: Role[] = [];
  
  productLineRoleKeys.forEach((productLineRoleKey) => {
    
    // 当前产品线对应的角色列表数据
    const currentProductLineRoleList = productLineMap[productLineRoleKey as SHBProductLineEnum]
    // 是否有当前产品线对应的角色列表数据
    const isHaveProductLine = Boolean(currentProductLineRoleList);
    
    if (isHaveProductLine) {
      
      const newRole: Role = {
        ...ProductLineRoleMap[productLineRoleKey],
        children: currentProductLineRoleList
      }
      
      newRoleList.push(newRole);
      
    }
    
  });
  
  return newRoleList;
}

export {
  roleToOption,
  rolesToOptions,
  transformRoleList
}
